<template>
	<Header :title="t('setting.title')" />
	<view class="main-box">
		<view class="u-page__item">
			<up-collapse @change="changeTimeGroup" @close="handleClose">
				<up-collapse-item disabled @click="isLogout">
					<template #title>
						<text class="title">{{ t("setting.cancel") }}</text>
					</template>
				</up-collapse-item>
				<up-collapse-item>
					<template #title>
						<text class="title">{{ t("setting.lang") }}</text>
					</template>
					<view class="u-collapse-content">
						<up-radio-group
							v-model="lanvalue"
							placement="column"
							iconPlacement="right">
							<up-radio
								:customStyle="{ marginBottom: '8px' }"
								v-for="(item, index) in lanlist"
								:key="index"
								:label="item.name"
								:name="item.value"
								labelColor="rgba(0, 0, 0, 0.9)"
								@change="lanChange"></up-radio>
						</up-radio-group>
					</view>
				</up-collapse-item>
				<up-collapse-item :title="t('setting.timeZone')">
					<view class="u-collapse-content">
						<scroll-view
							scroll-y
							:scroll-into-view="'radio-' + selTimezone"
							class="time-box">
							<up-radio-group
								v-model="timevalue"
								placement="column"
								iconPlacement="right">
								<up-radio
									:customStyle="{ marginBottom: '8px' }"
									v-for="(item, index) in timeList"
									:key="index"
									:label="item.region"
									:id="'radio-' + index"
									:name="item.tz"
									labelColor="rgba(0, 0, 0, 0.9)"
									@change="
										timeChange($event, index)
									"></up-radio>
							</up-radio-group>
						</scroll-view>
					</view>
				</up-collapse-item>
			</up-collapse>
		</view>
		<view class="bottom-box" @click="showModal">
			<text>{{ t("setting.signOut") }}</text>
		</view>
	</view>
	<TipsModal
		v-if="show"
		:contentText="t('setting.signOutInfo')"
		@handleCancel="handleCancel"
		@handleConfirm="handleConfirm" />
	<TipsModal
		v-if="showRemove"
		type="warn"
		:title="t('warning')"
		:contentText="t('setting.logoutInfo')"
		@handleCancel="cancelRemove"
		@handleConfirm="confirmRemove" />
	<up-loading-icon :show="showLoading"></up-loading-icon>
</template>

<script setup lang="ts">
import { userDel, userLogout, updateInfo } from "@/service/index";
import { ref, getCurrentInstance, reactive, onMounted, nextTick } from "vue";
import Header from "@/components/header/index.vue";
import TipsModal from "@/components/tipsModal/index.vue";
import { getPlatformDefaultId, safeGetPushId } from "@/utils/push";
import moment from "moment-timezone";
interface TimezoneItem {
	offsetMin: number;
	tz: string;
	regionName: string;
}

interface TimezoneOption {
	region: string;
	tz: string;
}
// 国际化
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();
const timeList = ref<TimezoneOption[]>([]);
const selTimezone = ref<number>(0);
const temporarilyIndex = ref<number>(0);
const instance: any = getCurrentInstance();
const show = ref(false);
const showRemove = ref(false);
const showLoading = ref(false);
const lanlist = reactive([
	{
		name: "中文",
		value: "zh",
	},
	{
		name: "English",
		value: "en",
	},
	{
		name: "한국의",
		value: "ko",
	},
	{
		name: "中文繁體",
		value: "zh-Hant",
	},
]);
const handleClose = () => {
	console.log("00");
	// isOpen.value = !isOpen.value; // 手动切换状态
};
const userInfoStore = useUniversalStorage("userinfo", {
	username: "",
	phone: "",
	staff_id: "",
	customer_type: "",
});
const lanvalue = ref<string>("");
const timevalue = ref<string>("");
const timeZoneStore = useUniversalStorage<string>(
	"SELECTED_TIMEZONE",
	"Asia/Shanghai"
);
const localeStore = useUniversalStorage<string>("LOCALE", "zh");
const lanChange = (value: any) => {
	lanvalue.value = value;
	nextTick(() => {
		localeStore.value = value;
		locale.value = value;
		// APP端
		// #ifdef APP-PLUS
		plus.runtime.restart();
		// #endif
		//#ifdef H5
		location.reload();
		//H5端只能进行模拟切换
		//#endif
	});
};
const timeChange = (value: any, index: number) => {
	temporarilyIndex.value = index;
	timevalue.value = value;
	timeZoneStore.value = value;
	handleClose();
};
const changeTimeGroup = (list: AnyArray) => {
	console.log(list);
	const status = list[2].status;
	if (status == "close") {
		selTimezone.value = temporarilyIndex.value;
	}
};

const layout = async (): Promise<void> => {
	const query = {
		unipush_cid: "",
	};
	// APP-PLUS 平台逻辑
	// #ifdef APP-PLUS
	if (instance?.proxy?.$appVersion !== "xz") {
		query.unipush_cid = safeGetPushId() || getPlatformDefaultId();
	}
	// #endif
	try {
		const { data } = await userLogout(query);
		if (!data.code) {
			instance?.proxy?.$message(t("setting.signOutSuccess"), "success");
			goLogin();
		}
	} catch (error) {
		console.error("Logout failed:", error);
	}
};
const showModal = () => {
	show.value = true;
};
const handleConfirm = () => {
	show.value = false;
	layout();
};
const isLogout = () => {
	showRemove.value = true;
};
const handleCancel = () => {
	show.value = false;
};
const cancelRemove = () => {
	showRemove.value = false;
};
const confirmRemove = async () => {
	const staff_id = userInfoStore.value.staff_id;
	const { data } = await userDel(
		{
			staff_id: staff_id,
		},
		staff_id
	);
	if (!data.code) {
		instance.proxy.$message(t("setting.logoutSuccess"), "success");
		goLogin();
	} else {
		instance.proxy.$message(t("setting.logoutFailed"), "error");
	}
	showRemove.value = true;
};

const goLogin = () => {
	// 存储数据
	userInfoStore.value = null;
	const tokenStore = useUniversalStorage("token", "");
	tokenStore.value = null;
	uni.reLaunch({
		url: "/pages/login/index",
	});
};
const getTimeList = async () => {
	timeList.value = await new Promise<TimezoneOption[]>((resolve) => {
		const scheduler =
			typeof requestIdleCallback !== "undefined"
				? requestIdleCallback
				: setTimeout;
		scheduler(() => {
			const rawList = moment.tz
				.names()
				.map((tz: string): TimezoneItem => {
					const now = moment.tz(tz);
					const offsetMin: number = now.utcOffset();
					let region: string =
						tz.split("/").pop()?.replace("_", " ") || tz;
					if (tz === "Asia/Shanghai") region = "北京";
					return {
						offsetMin,
						tz,
						regionName: region,
					};
				})
				.sort(
					(a: TimezoneItem, b: TimezoneItem) =>
						a.offsetMin - b.offsetMin
				)
				.map((item: TimezoneItem): TimezoneOption => {
					const sign: string = item.offsetMin >= 0 ? "+" : "-";
					const absMin: number = Math.abs(item.offsetMin);
					const hour: string = String(
						Math.floor(absMin / 60)
					).padStart(2, "0");
					const min: string = String(absMin % 60).padStart(2, "0");

					return {
						region: `(UTC${sign}${hour}:${min}) ${item.tz}`,
						tz: item.tz,
					};
				});
			resolve(rawList);
		});
	});
	// 延迟设置默认值
	nextTick(() => {
		timevalue.value ||= "Asia/Shanghai";
		const targetTz = timeZoneStore.value || timevalue.value;
		temporarilyIndex.value = timeList.value.findIndex(
			(item) => item.tz === targetTz
		);
		selTimezone.value = temporarilyIndex.value;
	});
};
onMounted(() => {
	lanvalue.value = localeStore.value || locale.value;
	getTimeList();
});
</script>

<style lang="scss" scoped>
.main-box {
	padding-top: 30rpx;
}
.bottom-box {
	position: fixed;
	bottom: 30px;
	width: 100%;
	height: 50px;
	line-height: 50px;
	text-align: center;
	background: #fff;
	text {
		color: #333;
		font-size: 16px;
	}
}
.u-page__item {
	background-color: #fff;
	:deep(.u-cell__right-icon-wrap--down) {
		transform: rotate(0deg);
	}
	:deep(.u-cell__right-icon-wrap--up) {
		transform: rotate(90deg);
	}
	.title {
		color: rgba(0, 0, 0, 0.9);
		font-size: 32rpx;
	}
	:deep(.u-collapse-item__content) {
		background-color: #f7f7f7;
	}
	:deep(.u-collapse-item__content__text) {
		padding: 0;
		padding-top: 30rpx;
	}
	:deep(.u-radio-group--column) {
		gap: 0 !important;
		background-color: #fff;
	}
	:deep(.u-radio-label--right) {
		padding: 30rpx 40rpx;
		border-bottom: 1px solid #e5e5e5;
		margin: 0 !important;
	}
	:deep(.u-radio-label--right:last-child) {
		border-bottom: 0;
	}
	.time-box {
		max-height: calc(100vh - 612rpx);
		overflow-y: auto;
	}
	:deep(.uni-scroll-view-content) {
		padding-bottom: 50px;
	}
}
</style>
